﻿using PLCS.Domain.Logs;
using PLCS.EquipmentService.BackgroundWorks.EquipmentRun;
using PLCS.EquipmentService.Models;
using PLCS.SocialHttpClient.WMS;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PLCS.EquipmentService.BackgroundWorks
{
    public class FailTaskReportAgainWorker : QuartzBackgroundWorkerBase
    {
        private readonly WMSSocialService _wMSSocialService;
        private readonly ILogger<FailTaskReportAgainWorker> _logger;

        public FailTaskReportAgainWorker(WMSSocialService wMSSocialService, ILogger<FailTaskReportAgainWorker> logger)
        {
            JobDetail = JobBuilder.Create<FailTaskReportAgainWorker>().WithIdentity(nameof(FailTaskReportAgainWorker)).Build();
            Trigger = TriggerBuilder.Create().WithIdentity(nameof(FailTaskReportAgainWorker))
                .WithSimpleSchedule(s => s.WithIntervalInSeconds(2)
                .RepeatForever()
                .WithMisfireHandlingInstructionIgnoreMisfires())
                .Build();

            ScheduleJob = async scheduler =>
            {
                if (!await scheduler.CheckExists(JobDetail.Key))
                {
                    await scheduler.ScheduleJob(JobDetail, Trigger);
                }
            };
            _wMSSocialService = wMSSocialService;
            _logger = logger;
        }

        public override async Task Execute(IJobExecutionContext context)
        {
            var failTasks = new List<FailTask>(GlobalModel.FailTaskIds);
            foreach (var item in failTasks)
            {
                try
                {
                    var result = await _wMSSocialService.ReportTaskAsync(item.TaskId, 2);
                    if (result.Header.Code == "S")
                    {
                        GlobalModel.FailTaskIds.Remove(item);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                }
            }
        }
    }
}